<?php

namespace app\tasks\service;
use app\common\ConfigBase;
use app\common\model\ToolModel;
use think\Db;

/**
 * 计划任务
 * xjy
 * @package app\tasks\controller
 */
class Syncoldskusystem
{
    /**每2分钟同步到旧sku资料库
     */
    static public function do()
    {
        $standard=array_flip(ConfigBase::$standard);
        $success=0;
        for($i=1;$i<2500;$i++){
            $skus=[];
            $categorySkus=[];//分类
            $statusSkuss=[];//销售状态
            $price=[];//参考价
            $weight=[];//打包前重量
            $asweight=[];//打包后重量

            $length=[];//打包前长
            $aslength=[];//打包后长

            $width=[];//打包前宽
            $aswidth=[];//打包后宽

            $height=[];//打包前高
            $asheight=[];//打包后高

            $skusVolume=[];//容量
            $skuMultiplicity=[];//多属性
            $skusStandard=[];//制式
            $skuEancode=[];//ean
            $qcStandard=[];//质检
            $uptime=[];//上架时间
            $update=[];//更新时间
            $skuEditor=[];//编辑信息
            $skuMultipleAttribute=[];//描述 卖点
            $res=Db::table('sys_sync_sku')->alias('c')
                ->field('b.*,a.*,c.id as sid')
                ->join('skus a','c.sku=a.sku')
                ->join('sku_attribute b','b.sku=c.sku')
                ->page($i,500)->select();

            if(empty($res)){
                break;
            }
            $skuIdArr=array_column($res,'sid');
            $skuArr=array_column($res,'sku');
            $spuArr=array_column($res,'spu');

            //新 老 uid对应
            $developer=array_column($res,'developer');
            $ssoName=Db::connect('db_sso')->table('_of_sso_user')->where(['id'=>['in',$developer]])->where("nike!=''")->column('id','name');// zhouting1 969760331
            $skuIdNameTemp=Db::connect('sku')->table('gleez.users')->where(['name'=>['in',array_keys($ssoName)]])->column('id','name');//zhouting1
            $skuIdName=[];
            foreach ($skuIdNameTemp as $k5=>$v5){
                $skuIdName[$ssoName[$k5]]=$v5;
            }
            $spuDb=Db::connect('sku')->table('spus')->where(['spu'=>['in',$spuArr]])->where(['spu'=>['<>',0]])->column('sku_ids,spu_id,spu','spu');
            $skuDb=Db::connect('sku')->table('skus')->where(['sku'=>['in',$skuArr]])->column('sku,id,isavailable','sku');
            $skuCnNameDb=Db::connect('sku')->table('sku_cnname')->where(['sku'=>['in',$skuArr]])->column('*','sku');
            $skuQcStandardDb=Db::connect('sku')->table('sku_qc_standard')->where(['sku'=>['in',$skuArr]])->column('qc_standard_id','sku');

            $newSKu=Db::table('manage_edit_audit')->where(['sku'=>['in',$skuArr],'assign_id'=>['>',0]])->column('id','sku');


            $skuMultipleAttributeDbTemp=Db::table('sku_multiple_attribute')->where(['sku'=>['in',$skuArr]])->field('sku,type,value_json')->select();
            $skuMultipleAttributeDb=[];
            $skuMultipleAttributeDbTitle=[];//标题模板
            $skuMultipleAttributeDbSmt=[];//速卖通属性
            $userSkus=[];
            foreach ($skuMultipleAttributeDbTemp as $v){
                if($v['type']==1){
                    $valueJsonTemp= str_replace(array('\r\n'),"<br>",$v['value_json']);
                    $valueJsonTemp= str_replace(array('\n'),"<br>",$valueJsonTemp);
                    $skuMultipleAttributeDb[$v['sku']]=$valueJsonTemp;
                }elseif ($v['type']==2){
                    $tempTitle=json_decode($v['value_json'],true);
                    if(!empty($tempTitle)){
                        $tempTitle['value']=str_replace('卍',' ',$tempTitle['value']);
                        $skuMultipleAttributeDbTitle[$v['sku']]=join(' ',$tempTitle['value']);
                    }
                }elseif ($v['type']==3){
                    $tempSmt=json_decode($v['value_json'],true);
                    $tempSmtStr='';
                    if(is_array($tempSmt['smtKeyValue'])){
                        foreach ($tempSmt['smtKeyValue'] as $k4=>$v4){
                            $tempSmtStr.="{$k4}:{$v4}<br/>";
                        }
                    }
                    $skuMultipleAttributeDbSmt[$v['sku']]=$tempSmtStr;
                }
            }
            foreach ($res as $v1){
                $success++;
                $skuData=[
                    'sku'=>$v1['sku'],
                    'isavailable'=>$v1['status'],
                    'date'=>$v1['creation_time'],
                    'modifytime'=>$v1['modification_time'],
                    'develop_num'=>$v1['develop_code'],
                    'develop_link'=>$v1['develop_link']
                ];
                if(empty($skuDb[$v1['sku']])){
                    $skuId=Db::connect('sku')->table('skus')->insertGetId($skuData);
                }else{
                    Db::connect('sku')->table('skus')->where('sku',$v1['sku'])->update($skuData);
                    $skuId=$skuDb[$v1['sku']]['id'];
                }
                if(empty($spuDb[$v1['spu']])){
                    $spuId=Db::connect('sku')->table('spus')->insertGetId(['spu'=>$v1['spu'],'sku_ids'=>$skuId]);
                }else{
                    $spuId=$spuDb[$v1['spu']]['spu_id'];
                    $skuIds=explode(',',$spuDb[$v1['spu']]['sku_ids']);
                    if(!in_array($skuId,$skuIds)){
                        Db::connect('sku')->table('spus')->where('spu_id',$spuId)->update(
                            ['sku_ids'=>Db::raw("concat(sku_ids,',',{$skuId})")]
                        );
                    }
                }
                Db::connect('sku')->table('skus')->where('sku',$v1['sku'])->update(['spu_id'=>$spuId]);
                $categorySkus[]=[
                    'sku'=>$v1['sku'],
                    'category_id'=>$v1['category_id']
                ];
                $price[]=[
                    'sku'=>$v1['sku'],
                    'num'=>$v1['reference_price']
                ];
                $statusSkuss[]=[
                    'sku'=>$v1['sku'],
                    'old_status_id'=>$v1['sales_status_old'],
                    'reason'=>$v1['remarks'],
                    'status_id'=>$v1['sales_status']
                ];
                $weight[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'g',
                    'num'=>$v1['asweight']
                ];
                $asweight[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'g',
                    'num'=>$v1['baleweight']
                ];
                $length[] =[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['aslength']
                ];
                $aslength[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['balelength']
                ];
                $width[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['aswide']
                ];
                $aswidth[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['balewide']
                ];
                $height[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['ashight']
                ];
                $asheight[]=[
                    'sku'=>$v1['sku'],
                    'var'=>'mm',
                    'num'=>$v1['balehight']
                ];
                $skusVolume[]=[
                    'sku'=>$v1['sku'],
                    'volume'=>$v1['bulk'],
                    'var'=>$v1['bulk_unit'],
                ];
                $skuMultiplicity[]=[
                    'sku_id'=>$skuId,
                    'color'=>$v1['color'],
                    'size'=>$v1['size'],
                    'pattern'=>$v1['pattern'],
                    'type'=>$v1['type'],
                    'shape'=>$v1['shape'],
                ];
                $skusStandard[]=[
                    'sku'=>$v1['sku'],
                    'standard_id'=>$standard[$v1['standard']]??'',
                ];
                $skuEancode[]=[
                    'sku'=>$v1['sku'],
                    'eancode'=>$v1['eancode']
                ];
                if(empty($v1['uptime'])||$v1['uptime']=='0000-00-00'){
                }else{
                    $uptime[]=[
                        'sku'=>$v1['sku'],
                        'uptime'=>$v1['uptime']
                    ];
                }
                $update[]=[
                    'sku'=>$v1['sku'],
                    'time'=>date('Y-m-d H:i:s')
                ];

                /*                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
                  `sku` varchar(25) NOT NULL COMMENT 'sku编码',
                  `accredit` varchar(10) NOT NULL COMMENT '是否授权',
                  `logo_describe` varchar(255) NOT NULL COMMENT '品牌logo',
                  `camera` varchar(25) NOT NULL COMMENT '摄影师',
                  `photo_designer` varchar(25) NOT NULL COMMENT '图片美工',
                  `english_editor` varchar(25) NOT NULL COMMENT '英文编辑',
                  `effect_editor` varchar(25) NOT NULL COMMENT '效果跟进员',
                  `storage_standards` text NOT NULL,'需求业务线'
                  `pic_level` varchar(255) NOT NULL COMMENT '图片资料分级',
                  `describe_level` varchar(255) NOT NULL COMMENT '描述资料分级',
                  `pic_allot` varchar(255) NOT NULL COMMENT '图片分配',
                  `edit_allot` varchar(255) NOT NULL COMMENT '编辑分配',
                  `edit_audit` varchar(255) NOT NULL COMMENT '编辑审核',
                  `oper_id` int(11) NOT NULL COMMENT '操作人员id',
                  `create_time` datetime NOT NULL COMMENT '创建时间',
                  `update_time` datetime NOT NULL COMMENT '修改时间',*/

                $skuEditor[]=[
                    'sku'=>$v1['sku'],
                    'accredit'=>$v1['authorization']?'是':'否',
                    'logo_describe'=>$v1['logo'],
                    'update_time'=>TIME
                ];

                if(!empty($skuIdName[$v1['developer']])){
                    $userSkus[]=[
                        'sku'=>$v1['sku'],
                        'modifytime'=>TIME,
                        'user_id'=>$skuIdName[$v1['developer']],
                        'serviceline'=>$v1['serviceline'],
                        'buyertype'=>1,
                    ];
                }
                $temp=$skuMultipleAttributeDb[$v1['sku']]??'';
                $temp=json_decode($temp,true);
                if(empty($temp['Features'])){
                    $Features='';
                }else{
                    if(empty($newSKu[$v1['sku']])){
                        $Features=$temp['Features'];
                    }else{
                        $Features=$temp['Features'].'<br/>';
                    }
                }
                if(empty($temp['Description'])){
                    $Description='';
                }else{
                    if(empty($newSKu[$v1['sku']])){
                        $Description=$temp['Description'];
                    }else {
                        $Description = $temp['Description'] . '<br/>';
/*                        $tempStr=substr($temp['Description'],-1,8);
                        if(strpos($tempStr,'p>')!==false||strpos($tempStr,'<br')!==false){
                            $Description = $temp['Description'] . '<br/>';
                        }else{
                            $Description = $temp['Description'] . '<br/><br/>';
                        }*/
                    }
                }
                if(empty($temp['Specifications'])){
                    $Specifications='';
                }else{
                    if(empty($newSKu[$v1['sku']])){
                        $Specifications=$temp['Specifications'];
                    }else {
                        $Specifications = $temp['Specifications'] . '<br/>';
                    }
                }
                if(empty($temp['Package Included'])){
                    $PackageIncluded='';
                }else{
                    if(empty($newSKu[$v1['sku']])){
                        $PackageIncluded=$temp['Package Included'];
                    }else {
                        $PackageIncluded = $temp['Package Included'] . '<br/>';
                    }
                }
                if(empty($temp['Notes'])){
                    $Notes='';
                }else{
                    if(empty($newSKu[$v1['sku']])){
                        $Notes=$temp['Notes'];
                    }else {
                        $Notes = $temp['Notes'] . '<br/>';
                    }
                }
                $skuMultipleAttribute[]=[
                    'sku'=>$v1['sku'],
                    'selling_points'=>$Features,
                    'description'=>$Description,
                    'specifications'=>$Specifications,
                    'package_included'=>$PackageIncluded,
                    'notes'=>$Notes,
                    'smt_attr'=>$skuMultipleAttributeDbSmt[$v1['sku']]??'',
                    'title_template'=>$skuMultipleAttributeDbTitle[$v1['sku']]??'',
                ];
                if(empty($skuCnNameDb[$v1['sku']])){
                    $cnNameId=Db::connect('sku')->table('cnname')->insertGetId(['name'=>$v1['name']]);
                    Db::connect('sku')->table('sku_cnname')->insertGetId(['sku'=>$v1['sku'],'attr_id'=>$cnNameId]);
                }else{
                    Db::connect('sku')->table('cnname')->where('id',$skuCnNameDb[$v1['sku']]['attr_id'])->update(['name'=>$v1['name']]);
                }
                Db::connect('sku')->table('supplier_skus')->where('sku',$v1['sku'])->update(['productname'=>$v1['name']]);

                if(empty($skuQcStandardDb[$v1['sku']])){
                    if(!empty($v1['qc_standard'])){
                        $qcStandardId=Db::connect('sku')->table('qc_standard')->insertGetId(['standard'=>$v1['qc_standard']]);
                        Db::connect('sku')->table('sku_qc_standard')->insertGetId(['sku'=>$v1['sku'],'qc_standard_id'=>$qcStandardId]);
                    }
                }else{
                    Db::connect('sku')->table('qc_standard')->where('id',$skuQcStandardDb[$v1['sku']])->update(['standard'=>$v1['qc_standard']]);
                }
            }
            ToolModel::dbInsertOrUpdate('category_skus',$categorySkus,[],'sku');
            ToolModel::dbInsertOrUpdate('price',$price,[],'sku');
            ToolModel::dbInsertOrUpdate('status_skuss',$statusSkuss,[],'sku');
            ToolModel::dbInsertOrUpdate('asweight',$asweight,[],'sku');
            ToolModel::dbInsertOrUpdate('weight',$weight,[],'sku');
            ToolModel::dbInsertOrUpdate('aslength',$aslength,[],'sku');
            ToolModel::dbInsertOrUpdate('length',$length,[],'sku');
            ToolModel::dbInsertOrUpdate('aswidth',$aswidth,[],'sku');
            ToolModel::dbInsertOrUpdate('width',$width,[],'sku');
            ToolModel::dbInsertOrUpdate('asheight',$asheight,[],'sku');
            ToolModel::dbInsertOrUpdate('height',$height,[],'sku');
            ToolModel::dbInsertOrUpdate('skus_volume',$skusVolume,[],'sku');
            ToolModel::dbInsertOrUpdate('sku_multiplicity',$skuMultiplicity,[],'sku');
            ToolModel::dbInsertOrUpdate('sku_eancode',$skuEancode,[],'sku');
            ToolModel::dbInsertOrUpdate('skus_ext',$skuMultipleAttribute,[],'sku');
            !empty($uptime)&&ToolModel::dbInsertOrUpdate('uptime',$uptime,[],'sku');
            ToolModel::dbInsertOrUpdate('sku_update',$update,[],'sku');
            ToolModel::dbInsertOrUpdate('skus_standard',$skusStandard,[],'sku');
            ToolModel::dbInsertOrUpdate('sku_editor',$skuEditor,[],'sku');
            !empty($userSkus)&&ToolModel::dbInsertOrUpdate('user_skus',$userSkus,[],'sku');
            Db::table('sys_sync_sku')->where(['id'=>['in',$skuIdArr]])->delete();
            //TODO 采购员user_skus
        }
        if($success>0){

        }
        $runtime = round(microtime(true) - THINK_START_TIME, 10);
        $msg= '成功数量'.$success.' 运行时间:'.number_format($runtime, 2) . '秒 ; 使用内存:'.number_format((memory_get_peak_usage() - THINK_START_MEM) / 1024 / 1024, 2) . ' ' .('MB');
        return returnArr(1,$msg);
    }

}
